--[[
	Fixed by egingell.
		Made functional with 2.0 and BC.
		Added Keyring support.
		Added icons to the tooltip, though only 8 will display.
		Added quantities.
		Grouped same-items onto one line.
		Fixed bank bags (B4nkFrameBag[1-7]). Typo on Blizzard's end? On purpose? Who knows.
			Thanks to "MoveAnything" for making that fix possible.
		Updated Ace libs.
--]]

local aName, aVer = "XRayVision", "0.1.0";
-- gtUpdate = nil;

local gt = GameTooltip
local XRayVision = CreateFrame("Frame")

XRayVision.clearTooltip = true

function XRayVision:SetClearTooltip()
	XRayVision.clearTooltip = (not XRayVision.clearTooltip)
end

function XRayVision:OnEnable()
	UIErrorsFrame:AddMessage(aName.." version "..aVer.." loaded.")
	
--[[ old way
	self:SecureHook("BagSlotButton_OnEnter")
	self:HookScript(GameTooltip, "OnUpdate")
	self:SecureHook("BankFrameItemButton_OnEnter")	
	self:HookScript(MainMenuBarBackpackButton, "OnEnter")
	self:HookScript(KeyRingButton, "OnEnter")
--]]
	for i = 0, 3 do
		_G["CharacterBag" .. i .. "Slot"]:HookScript("OnEnter", function(f)
			self:BagSlotButton_OnEnter(f)
		end)
	end
	for i = 1, 7 do
		_G["BankFrameBag" ..i]:HookScript("OnEnter", function(f)
			self:BagSlotButton_OnEnter(f, nil, true)
		end)
	end
	GameTooltip:SetScript("OnUpdate", function(f, elapsed)
		self:OnUpdate(f, elapsed)
	end)
	MainMenuBarBackpackButton:HookScript("OnEnter", function(f)
		self:BagSlotButton_OnEnter(f, 0)
	end)
	KeyRingButton:HookScript("OnEnter", function(f)
		self:BagSlotButton_OnEnter(f, KEYRING_CONTAINER)
	end)
	
	self:AddSlashCommand(aName, function(msg)
		msg = string.lower(msg)
		if msg == "toggle cleartooltip" then
			self:SetClearTooltip()
		else
			ChatFrame1:AddMessage("[" .. aName .. "] Usage: ")
			ChatFrame1:AddMessage("/xray toggle cleartooltip")
		end
	end, "/xrayvision", "/xray");
end

function XRayVision:OnUpdate(f, elapsed)
	-- Only update every TOOLTIP_UPDATE_TIME seconds
	f.updateTooltip = f.updateTooltip - elapsed;
	if ( f.updateTooltip > 0 ) then
		return;
	end
	f.updateTooltip = TOOLTIP_UPDATE_TIME;

	local owner = f:GetOwner();
	if ( owner and owner.UpdateTooltip and not owner.isBag ) then
		owner:UpdateTooltip();
	end
end

function XRayVision:BagSlotButton_OnEnter(f, backpack, isBank)
	if not gt:IsShown() then
--		gt:SetOwner(self, "ANCHOR_TOPRIGHT", gt:GetWidth() + 10, 0)
		GameTooltip_SetDefaultAnchor(gt, f)
	end
	-- Clear the current contents of the tooltip.
	-- If it's being used, I don't care what other addons have to say about it.
	-- If you don't want to clear the tooltip, type "/xray cleartooltip".
	if XRayVision.clearTooltip then
		gt:ClearLines();
	end
	
	local bag;
	if (backpack == 0) then
		bag = backpack;
	elseif isBank or backpack == KEYRING_CONTAINER then
		bag = f:GetID()
	else
		bag = f:GetID() - 19;
	end

--	UIErrorsFrame:AddMessage(bag);
	local items = {}
	local bagName = GetBagName(bag);
	local numBagSlots = GetContainerNumSlots(bag);
	local bagLink;
	--<<
	-- From here to "-->>" we are getting the name of the bag to add to the tooltip or '[Empty Slot]' if
	-- there's no bag.
	if (bagName) then
		_, bagLink = GetItemInfo(bagName);
	else
		if (bag == KEYRING_CONTAINER) then
			bagLink = '[' .. KEYRING .. ']';
		else
			bagLink = '[Empty Slot]';
		end
	end
	if (not bagLink) then -- it must be the backpack
		bagLink = '[Backpack]';
	end
	-->>
	local at_least_one = false;
	for i = 1, numBagSlots do
		local link = GetContainerItemLink(bag, i);
		if link then
			local itemName, itemLink, _, _, _, _, _, _, _, texture = GetItemInfo(link);
			local _, itemCount = GetContainerItemInfo(bag, i);
			at_least_one = true;
			if (itemName and not items[itemName]) then
				items[itemName] = {};
			end
			items[itemName].texture = texture;
			items[itemName].itemLink = link;
			if (items[itemName].count) then
				items[itemName].count = items[itemName].count + itemCount;
			else
				items[itemName].count = itemCount;
			end
		end
	end
	table.sort(items, function(a,b)
		--local a1 = string.gsub(a, "%[(.-)%]", "%1")
		--local b1 = string.gsub(b, "%[(.-)%]", "%1")
		return a < b
	end)
	-- There's no reason not to add the bag name.
	-- If clearTooltip is false, replace line 1, instead of add it.'
	if XRayVision.clearTooltip then
		gt:AddLine(bagLink..' '..numBagSlots..' Slots')
	else
		GameTooltipTextLeft1 = nil
		GameTooltipTextRight1 = nil
		GameTooltipTextLeft1 = bagLink..' '..numBagSlots..' Slots'
	end
	local nextLine = gt:NumLines() + 1;
	-- Don't add the header unless there's at least one item in the items table.
	if (at_least_one) then
		gt:AddLine('== Bag Contents ==')
		for itemName,t_items in pairs(items) do
			if (t_items.count > 1) then
				t_items.count = 'x'..tostring(t_items.count);
			else
				t_items.count = '';
			end
			t_items.itemLink = gsub(t_items.itemLink, "%[(.*)%]", "|T"..t_items.texture..":0:0:0:0|t\032[%1]")
			gt:AddDoubleLine(" "..t_items.itemLink, t_items.count);
			--gt:AddTexture(t_items.texture);
		end
--[[ Try this again, some day
		local f
		local id = 1
		for itemName,t_items in pairs(items) do
			
			f = CreateFrame("Frame", "XRayFontString" .. id, nil, "XRayGameTooltipFontString")
			_G[f:GetName() .. "TextLeft"]:SetWidth(UIParent:GetWidth())
			_G[f:GetName() .. "TextRight"]:SetWidth(0)
			id = id + 1
			GameTooltip:AddFontStrings(_G[f:GetName() .. "TextLeft"], _G[f:GetName() .. "TextRight"])
--			if (t_items.count > 1) then
				t_items.count = tostring(t_items.count)..'x';
--			else
--				t_items.count = '';
--			end
			
			gt:AddLine("|T"..t_items.texture..":0:0:0:0|t"..t_items.count..t_items.itemLink)
--			gt:AddTexture(t_items.texture);
		end
--]]
		gt:AddLine('==================')
	end
	gt:Show()
end

function XRayVision:AddSlashCommand(name, func, ...)
	SlashCmdList[name] = func
	local command = ''
	for i = 1, select('#', ...) do
		command = select(i, ...)
		if strsub(command, 1, 1) == '/' then
			command = strsub(command, 2)
		end
		_G['SLASH_'..name..i] = '/' .. command
	end
end

XRayVision:OnEnable()

_G["XRayVision"] = XRayVision
